package current.aqs;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

public class SemaphoreDemo {
    static class Semaphore extends AbstractQueuedSynchronizer {
        public Semaphore(int permit) {
            setState(permit);
        }

        @Override
        protected int tryAcquireShared(int arg) {
            int available = getState();
            if (available == 0) {
                return -1;
            }
            // 每进入一个线程available减一
            int left = available - 1;
            if (compareAndSetState(available, left)) {
                // 如果成功了就返回
                return left;
            }
            return -1;
        }

        @Override
        protected boolean tryReleaseShared(int arg) {
            int available = getState();
            return compareAndSetState(available, available + 1);
        }
    }

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 1000; i++) {
            new Thread(() -> {
                semaphore.acquireShared(0);
                try {
                    System.out.println("go");
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                semaphore.releaseShared(0);
            }).start();
        }
    }
}
